package App.Service;

import App.Entity.Auth;
import App.Entity.Person;
import App.Exception.PasswordErrorException;
import App.Exception.UserExistException;
import App.Exception.UserNotExistException;
import App.Repository.AuthRepository;
import App.Repository.PersonRepository;
import App.Utils.Security.Decrypt;
import App.Utils.Security.Encrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证服务
 * Created by yu on 2017/7/17.
 */
@Service
public class AuthService
{
    @Autowired
    AuthRepository authRepository;
    @Autowired
    PersonRepository personRepository;
    private Long nowId;
    public Long register(String email, String password){
        Map<String,Object> res=new HashMap<>(3);
        Auth auth=new Auth(email,Encrypt.encryptPassword(password));
        authRepository.save(auth);
        personRepository.save(new Person(auth.getId()));
        return auth.getId();
    }

    public Map<String,Object> login(String email, String password, HttpSession session){
        HashMap<String,Object> res=new HashMap<>();
        Auth auth=authRepository.getAuthByEmail(email);
        if(auth==null)
        {
          res.put("error","用户不存在");
          res.put("errorType","UserNotExistError");
          return res;
        }
        else if(!Decrypt.checkPassword(password,auth.getPassword())){
            res.put("error","密码错误");
            res.put("errorType","PasswordError");
            return res;
        }
        res.put("success",auth.getId());
        return res;
    }

    public boolean existUser(String Email){
        return authRepository.getAuthByEmail(Email) !=null;
    }


    public Long getNowId() {
        return nowId;
    }

    public void setNowId(Long nowId) {
        this.nowId = nowId;
    }
}
